import json
import os
import shutil
import traceback

from logger import logger

LOGGER = logger.CustomLogger()

class OwnerConfigMgr:
    def __init__(self, user_agent):
        self.owner_config = {}
        self.user_agent = user_agent
        self.load_owner_config()

    def backup_owner_config(self):
        try:
            file_path = 'config/' + self.user_agent.replace("-", "_") + '/owner_config.json'
            if not os.path.exists(file_path):
                raise FileNotFoundError(f"Source file not found: {file_path}")

            base_name = os.path.basename(file_path)
            backup_name = f"{base_name}.bak"
            backup_path = os.path.join(os.path.dirname(file_path), backup_name)

            shutil.copy2(file_path, backup_path)
            LOGGER.info("[sys] Backup success.")
        except Exception as e:
            LOGGER.error(f"[sys] Backup failed: {str(e)}")

    def restore_owner_config(self, backup_path):
        try:
            # 验证备份文件存在且是.bak文件
            if not backup_path.endswith('.bak'):
                raise ValueError("必须提供.bak后缀的备份文件")
            if not os.path.exists(backup_path):
                raise FileNotFoundError(f"备份文件不存在: {backup_path}")

            # 生成原始文件名（去掉.bak）
            original_path = backup_path[:-4]

            # 执行恢复操作
            shutil.copy2(backup_path, original_path)
        except Exception as e:
            LOGGER.error(f"[sys] Restore failed: {str(e)}")

    def load_owner_config(self):
        file_path = 'config/' + self.user_agent.replace("-", "_") + '/owner_config.json'
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                self.owner_config = json.load(file)
                for group, members in self.owner_config.get("groups").items():
                    for member in members:
                        if member not in self.owner_config["userInfos"]:
                            self.owner_config["userInfos"][member] = {}
                        if "group" not in self.owner_config["userInfos"][member]:
                            self.owner_config["userInfos"][member]["group"] = []
                        self.owner_config["userInfos"][member]["group"].append(group)
        except Exception as e:
            self.restore_owner_config(file_path + ".bak")
            LOGGER.error(f"[sys] update {file_path} file failed, error details: {traceback.format_exc()}")
